/*
 * CHttpClient.h
 *
 *  Created on: 2017年3月31日
 *      Author: chuanjiang.zh
 */

#ifndef CHTTPCLIENT_H_
#define CHTTPCLIENT_H_

#include "BasicType.h"
#include "HttpClient.h"
#include "TThread.h"
#include "HttpAfx.h"


class CHttpClient : public HttpClient, public comn::Thread
{
public:
	static const int TIMEOUT = 5000;	// milliseconds

public:
	CHttpClient();
	virtual ~CHttpClient();

	virtual bool request(const std::string& url, const std::string& httpMethod, const StringMap& headers, const std::string& body,
		HttpClientCallback cb);


	virtual void close();

	virtual bool isOpen();

	virtual void setTimeout(int seconds);

	static bool parseStatusCode(const char* data, size_t size, int& code);

public:

	void handleEvent(struct mg_connection *nc, int ev, void *ev_data);

    struct HttpContext
    {
        HttpClientCallback  cb;
        mg_connection* connection;

        HttpContext():
            cb(),
            connection()
        {
        }
    };

    typedef comn::Map< mg_connection*, HttpContext>     HttpContextMap;

protected:
	virtual int run();
    virtual void doStop();

	void fireCallback(HttpContext& context, int code, const char* data, size_t length, const http_message* msg);
    bool fireCallback(struct mg_connection *nc, int code, const char* data, size_t length, const http_message* msg);

	void breakPoll();

protected:
	struct mg_mgr m_mgr;
    HttpContextMap  m_contextMap;
	int m_timeout;

};

#endif /* CHTTPCLIENT_H_ */
